<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Shop\Api;
use Common\Api\Api;
use Shop\Model\ProductMemberPriceModel;
use Shop\Model\ProductModel;
use Shop\Model\ProductSkuModel;
use Think\Model;


class ProductSkuApi extends Api{

    //减少库存
    const SET_DEC="Shop/ProductSku/setDec";
    //增加库存
    const SET_INC="Shop/ProductSku/setInc";

    /**
     * 判断是否多规格
     */
    const HAS_SKU = "Shop/ProductSku/hasSku";

    /*
     * 获取多规格id
     * */
    const GET_SKU_ID = "Shop/ProductSku/getSkuId";

    /**
     * 获取多规格名称
     */
    const GET_SKU_NAME = "Shop/ProductSku/getSkuName";

    /**
     * 判断是否添加了规格信息
     */
    const IS_SKU = "Shop/ProductSku/isSku";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/ProductSku/queryNoPaging";
    /**
     * 添加
     */
    const ADD = "Shop/ProductSku/add";
    /**
     * 保存
     */
    const SAVE = "Shop/ProductSku/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/ProductSku/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/ProductSku/delete";

    /**
     * 查询
     */
    const QUERY = "Shop/ProductSku/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/ProductSku/getInfo";
    /**
     * 保存sku数据
     */
    const ADD_SKU_LIST = "Shop/ProductSku/addSkuList";

    /**
     * 查询一条数据带会员价
     */
    const GET_INFO_WITH_MEMBER_PRICE = "Shop/ProductSku/getInfoWithMemberPrice";

    /**
     * 查询不分页，带会员价
     */
    const QUERY_NO_PAGING_WITH_MEMBER_PRICE = "Shop/ProductSku/queryNoPagingWithMemberPrice";

    /**
     *
     */
    protected function _init(){
		$this->model = new ProductSkuModel();
	}

    /**
     * 上架前判断是否添加了sku信息
     * @param bool|false $pid
     * @return 0,1
     */
    public function isSku($pid = false){
        if($pid === false){
            return $this -> apiReturnErr("缺少商品id参数");
        }
        $map = array('product_id' => $pid);
        $result = $this -> model -> where($map) -> count();

        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        if($result == 0){
            return $this -> apiReturnSuc(0);
        }else{
            return $this -> apiReturnSuc(1);
        }
    }

    /**
     * 判断是否多规格
     * @param $pid
     */
    public function hasSku($pid = false){

        if($pid === false){
            return $this -> apiReturnErr("缺少商品id参数");
        }

        $map = array('product_id'=>$pid);

        $list = $this -> model -> where($map) ->select();

        if($list === false){
            $error = $this -> model ->getDbError();
            return $this -> apiReturnErr($error);
        }

        if(is_null($list)){
            return $this -> apiReturnSuc(0);
        }
        if(count($list) == 1 && $list[0]['sku_id'] == ""){
            return $this -> apiReturnSuc(0);
        }

        return $this -> apiReturnSuc(1);

    }

    /**
     * 获取商品skuId信息
     * @param $pid 商品id
     * @return json
     */
    public function getSkuId($pid = false,$field = false){

        if($pid === false){
            return $this -> apiReturnErr("缺少商品id参数");
        }
        if($field === false){
            return $this -> apiReturnErr("缺少字段参数");
        }

        $map = array('product_id'=>$pid);

        $list = $this -> model -> where($map) -> field($field) ->select();

        if($list === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $res = $this-> getSkuJson($list,$field);

        return $this -> apiReturnSuc($res);

    }

    /**
     * 获取规格名称
     * @param bool|false $pid
     * @param bool|false $field
     * @return array
     */
    public function getSkuName($pid = false,$field = false){

        if($pid === false){
            return $this -> apiReturnErr("缺少商品id参数");
        }

        if($field === false){
            return $this -> apiReturnErr("缺少字段参数");
        }

        $map = array('product_id' => $pid);

        $list = $this -> model -> where($map) -> field($field) -> select();

        if($list === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $res = $this -> getSkuJson($list,$field);

        return $this -> apiReturnSuc($res);

    }

    private function getSkuJson($list,$field){
        //进行数组整合
        $result = array();
        foreach($list as $vo){
            $tmp = explode(';',$vo[$field]);
            array_pop($tmp);
            foreach ($tmp as $k => $v) {
                if(is_null($result[$k])){
                    $result[$k] = array();
                }
                array_push($result[$k],$v);
            }
        }

        //去重
        foreach($result as $k => $v){
            $result[$k] = array_unique($v);
        }

        /*
         $result =
         array(
            [0]array(
                [0] => "k0:v01",
                [1] => "k0:v02",
                [2] => "k0:v03",
                ...
            ),
            [1]array(
                [0] => "k1:v11",
                [1] => "k1:v12",
                [2] => "k1:v13",
                ...
            ),
            [2]array(
                [0] => "k2:v21",
                [1] => "k2:v22",
                [2] => "k2:v23",
                ...
            ),
            ...
        )
         * */

        $res = array();
        $flag = array();
        $i = 0;
        foreach ($result as $k => $v) {
            foreach($v as $kk => $vv){
                $tmp = explode(':',$vv);
                if(is_null($flag[$tmp[0]])){
                    $flag[$tmp[0]] = $i;
                    $i++;
                    $res[$flag[$tmp[0]]]['id'] = $tmp[0];
                }
                if(is_null($res[$flag[$tmp[0]]]['vid'])){
                    $res[$flag[$tmp[0]]]['vid'] = array();
                }
                array_push($res[$flag[$tmp[0]]]['vid'],$tmp[1]);
            }
        }
        /*
        $res =
        array(
            [0]array(
                id => k0,
                vid => array(
                    [0] => v01,
                    [1] => v02,
                    [2] => v03
                    ...
                )
            ),
            [1]array(
                id => k1,
                vid => array(
                    [0] => v11,
                    [1] => v12,
                    [2] => v13,
                    ...
                )
            ),
            [2]array(
                id => k2,
                vid => array(
                    [0] => v21,
                    [1] => v22,
                    [2] => v23,
                    ...
                )
            ),
            ...
        )
         * */

        return json_encode($res);
    }


    /**
     * 保存sku数据
     * @param $id
     * @param $sku_info
     * @param $list
     * @return array
     */
    public function addSkuList($id,$has_sku,$list){

        //删除表内原有相关数据
        $this->model->startTrans();
        $flag = true;
        $error = "";
        $map = array('product_id'=>$id);

        $result = $this->model->where($map)->delete();
        if($result === false){
            $flag = false;
            $error = $this->model->getDbError();
        }

        //清除会员价
        $MemberPrice = new ProductMemberPriceModel();
        $map = array('p_id'=>$id);
        $result = $MemberPrice->where($map)->delete();
        if($result === false){
            $flag = false;
            $error = $this->model->getDbError();
        }

        //重新插入数据
        if($has_sku == 0){
            //统一规格
            $entity = array(
                'product_id' => $id,
                'sku_id' => '',
                'ori_price' => $list['ori_price'],
                'price' =>($list['price']*100) ,
                'cnt1' => $list['cnt1'],
                'price2' => ($list['price2']*100),
                'cnt2' => $list['cnt2'],
                'price3' => ($list['price3']*100),
                'cnt3' => $list['cnt3'],
                'quantity' => $list['quantity'],
                'product_code' => $list['product_code'],
                'icon_url' => '',
                'sku_desc' => "",
                'taxation' => $list['taxation']
            );

            if($this -> model -> create($entity,1)){
                $result = $this -> model -> add();
                if($result !== false){

                    if($result !==false){
                        $sku_id = $result;
                        foreach($list['member_price'] as $vo){
                            //插入会员价数据
                            $entity = array(
                                'p_id' => $id,
                                'member_group_id' => $vo['member_group_id'],
                                'sku_id' => $sku_id,
//                                'price' => $vo['price']
                            );
                            if($MemberPrice -> create($entity,Model::MODEL_INSERT)){
                                $result = $MemberPrice-> add();
                                if($result === false){
                                    $flag = false;
                                }
                            }
                            if(!$flag) break;
                        }
                        if($flag){
                            $this -> model -> commit();
                            return $this -> apiReturnSuc('保存成功');
                        }

                    }
                }
            }
            $error = $this -> model -> getDbError();
            $this -> model -> rollback();
            return $this -> apiReturnErr($error);

        }else{
            //多规格
            foreach($list as $vo){
                $entity = array(
                    'product_id'=>$id,
                    'sku_id'=>$vo['sku_id'],
//                    'ori_price'=>$vo['ori_price'],
                    'price'=>($vo['price']*100),
                    'cnt1'=>$vo['cnt1'],
                    'price2'=>($vo['price2']*100),
                    'cnt2'=>$vo['cnt2'],
                    'price3'=>($vo['price3']*100),
                    'cnt3'=>$vo['cnt3'],
                    'quantity'=>$vo['quantity'],
                    'product_code'=>$vo['product_code'],
                    'icon_url'=>$vo['icon_url'],
                    'sku_desc'=>$vo['sku_desc'],
                    'taxation'=>$vo['taxation']
                );

                if($this->model->create($entity,1)){
                    $result = $this->model->add();
                    if($result === false){
                        $flag = false;
                        $error = $this->model->getError();
                    }else{
                        $sku_id = $result;
                        foreach($vo['member_price'] as $xo){
                            //插入会员价数据
                            $entity = array(
                                'p_id' => $id,
                                'member_group_id' => $xo['member_group_id'],
                                'sku_id' => $sku_id,
//                                'price' => $xo['price']
                            );
                            if($MemberPrice -> create($entity,Model::MODEL_INSERT)){
                                $result = $MemberPrice-> add();
                                if($result ===false){
                                    $flag = false;
                                    $error = $this->model->getError();
                                }
                            }
                            if(!$flag) break;
                        }

                    }
                }else{
                    $flag = false;
                    $error = $this->model->getError();
                }

            }

            if($flag){
                $this->model->commit();
                return $this->apiReturnSuc($result);
            }else{
                $this->model->rollback();
                return $this->apiReturnErr($error);
            }
        }
    }



    /*public function addSkuList($id,$sku_info,$list){
        $this->model->startTrans();
        $sql = "";
        $flag = true;
        $error = "";
        $map = array('product_id'=>$id);

        $result = $this->model->where($map)->delete();
        if($result === false){
            $flag = false;
            $error = $this->model->getDbError();
        }

        foreach($list as $vo){
            $entity = array(
                'product_id'=>$id,
                'sku_id'=>$vo['sku_id'],
                'ori_price'=>$vo['ori_price'],
                'price'=>$vo['price'],
                'quantity'=>$vo['quantity'],
                'product_code'=>$vo['product_code'],
                'icon_url'=>$vo['icon_url'],
                'sku_desc'=>$vo['sku_desc'],
            );

            if($this->model->create($entity,1)){
                $result = $this->model->add();
                if($result === false){
                    $flag = false;
                    $error = $this->model->getError();
                }
            }else{
                $flag = false;
                $error = $this->model->getError();
            }

        }


        if($flag){
            //更新 产品信息
            $entity = array(
                'has_sku'=>1,
                'sku_info'=>json_encode($sku_info,JSON_UNESCAPED_UNICODE),
            );
            $map = array('id'=>$id);
            $model = new ProductModel();
            $result = $model->where($map)->save($entity);
            if($result === false){
                $flag = false;
                $error = $this->model->getDbError();
            }
        }


        if($flag){
            $this->model->commit();
            return $this->apiReturnSuc($result);
        }else{
            $this->model->rollback();
            return $this->apiReturnErr($error);
        }

    }*/

    /**
     * 获取数据find 带会员价格
     */
    public function getInfoWithMemberPrice($map,$order=false){
        if($order === false){
            $result = $this -> model -> where($map)-> find();
        }else{
            $result = $this->model->  where($map)-> order($order) -> find();
        }
        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        } else {

            //查询会员价
            $sku = $result;
            if($sku!=null){
                $result = apiCall(ProductMemberPriceApi::QUERY_NO_PAGING, array(array('sku_id'=>$sku['id'])));
                if($result['status']){
                    $sku['member_price'] = $result['info'];
                }
            }
            return $this -> apiReturnSuc($sku);
        }
    }

    /**
     * query 不分页 带会员价格
     * @param $map 查询条件
     * @param $order 排序条件
     * @param $fields 只获取指定字段
     */
    public function queryNoPagingWithMemberPrice($map = null, $order = false) {
        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }

        $query = $query->field($fields);

        $list = $query -> alias('sku') ->join($join,'LEFT') -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        //查询会员价
        $sku_list = $list;
        if($sku_list!=null){

            foreach ($sku_list as &$val){

                $result = apiCall(ProductMemberPriceApi::QUERY_NO_PAGING, array(array('sku_id'=>$val['id'])));
                if($result['status']){
                    $val['member_price'] = $result['info'];
                }

            }
        }

        return $this -> apiReturnSuc($sku_list);

    }

}
